題目:
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
The area of the rectangular web page you designed must equal to the given target area.
The width W should not be larger than the length L, which means L >= W.
The difference between length L and width W should be as small as possible.
Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.
給定一方形的面積,回傳符合面積的[長,寬]
其中長寬為整數,長要大於寬,且長寬差距越小越好
長寬差距越小越好,表示長寬要盡量接近正方形
class Solution:
def constructRectangle(self, area: int) -> List[int]:
x=int(sqrt(area))
while True:
if area%x==0:
return [area//x,x]
else:
x=x-1
我們由寬(x)為int(sqrt(area))開始推
即由正方形慢慢往長方形的方向推
直到area能被x整除為止,x不斷減1
一旦能整除代表我們發現了差距最小的長寬,立即回傳當下長寬
最後執行時間36ms(faster than 91.88%)
那我們下題見